#include <iostream>
#include <memory>

using std::cout;
using std::endl;
using std::shared_ptr;
using std::weak_ptr;

//weak_ptr是弱引用指针，通常和shared_ptr一起使用
//解决方法将其中一个改为weak
class Child;
class Parent{
public:
    Parent(){
        cout<<"Parent()"<<endl;
    }

    ~Parent(){
        cout<<"~Parent()"<<endl;
    }

    shared_ptr<Child> _sChild;
};

class Child{
public:
    Child(){
        cout<<"Child()"<<endl;
    }

    ~Child(){
        cout<<"~Child()"<<endl;
    }

    weak_ptr<Parent> _wParent;    //你包含我我包含你
};

void test(){
    shared_ptr<Parent> spParent(new Parent());  //栈对象
    shared_ptr<Child> spChild(new Child());
    cout<<"spParent.use_count()="<<spParent.use_count()<<endl;
    cout<<"spChild.use_count()="<<spChild.use_count()<<endl;

    cout<<endl;
    spParent->_sChild=spChild;  //赋值
    spChild->_wParent=spParent; 
    cout<<"spParent.use_count()="<<spParent.use_count()<<endl;//weak不会增加count
    cout<<"spChild.use_count()="<<spChild.use_count()<<endl;
    //析构的顺序取决于weak在哪，
    //拥有weak的那一方要等到对面先销毁，自己的count变为0，才能析构
}

int main()
{   
    test();
    return 0;
}

